<template>
  <div class="character-detail">
    <div class="header">
      <el-button class="back-btn" @click="goBack">
        <el-icon><ArrowLeft /></el-icon>
      </el-button>
      <div class="actions">
        <el-button class="collect-btn" :class="{ collected: isCollected }" @click="toggleCollect">
          <el-icon><Star /></el-icon>
        </el-button>
      </div>
    </div>

    <div class="main-content">
      <div class="character-showcase">
        <div class="image-container">
          <img :src="currentImage" 
               :alt="currentCharacter" 
               class="character-image" 
               :class="{ 
                 'black-and-white': isBlackAndWhite,
                 'with-grid': selectedGrid !== 'none'
               }" 
               ref="mainImage"/>
          <div v-if="selectedGrid !== 'none'" 
               :class="['grid-overlay', `grid-${selectedGrid}`]">
          </div>
        </div>
        <h1 class="character">{{ currentCharacter }}</h1>
        
        <div class="function-buttons">
          <div class="function-item">
            <button class="function-btn" @click="downloadImage">下载</button>
          </div>
          <div class="function-item">
            <button class="function-btn" :class="{ active: isBlackAndWhite }" @click="toggleBlackAndWhite">
              {{ isBlackAndWhite ? '原色' : '黑白' }}
            </button>
          </div>
          <div class="function-item">
            <button class="function-btn" 
                    :class="{ active: selectedGrid !== 'none' }" 
                    @click="toggleGridMenu">
              {{ selectedGrid === 'none' ? '线格' : '关闭' }}
            </button>
          </div>
          <div class="function-item">
            <button class="function-btn">同字搜索</button>
          </div>
        </div>
      </div>

      <div class="info-section">
        <div class="info-card">
          <div class="character-grid">
            <div v-for="(char, index) in nextCharacters" 
                 :key="char.id" 
                 class="similar-char-item"
                 @click="selectPreviewImage(index)">
              <img :src="char.image" :alt="char.title"/>
              <span>{{ char.title }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <el-dialog
      v-model="showGridMenu"
      title="选择线格样式"
      width="400px"
      align-center
      :show-close="false"
      class="grid-dialog"
    >
      <div class="grid-options">
        <div class="grid-option" 
             v-for="option in gridOptions" 
             :key="option.value"
             :class="{ active: tempSelectedGrid === option.value }"
             @click="selectGrid(option.value)">
          <div class="grid-preview" :class="`preview-${option.value}`">
            <template v-if="option.value === 'square'">
              <div v-for="i in 9" :key="i"></div>
            </template>
          </div>
          <span>{{ option.label }}</span>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button class="dialog-btn" @click="showGridMenu = false">取消</el-button>
          <el-button class="dialog-btn" type="primary" @click="confirmGridSelection">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { 
  ArrowLeft, 
  Star, 
  Download, 
  Grid, 
  MoonNight, 
  Search 
} from '@element-plus/icons-vue'
import ziIcon from '@/assets/zi_icon.png'
import { saveAs } from 'file-saver'
import type { Ref } from 'vue'

const route = useRoute()
const router = useRouter()
const isCollected = ref(true)
const isBlackAndWhite = ref(false)
const mainImage = ref<HTMLImageElement | null>(null)
const selectedGrid = ref<'none' | 'square' | 'field' | 'star'>('none')
const showGridMenu = ref(false)

const gridOptions = [
  { label: '方格', value: 'square' },
  { label: '田字格', value: 'field' },
  { label: '米字格', value: 'star' }
] as const

const tempSelectedGrid = ref<'none' | 'square' | 'field' | 'star'>('none')

// 添加一个数组来存储所有字符数据
const allCharacters = [
  { 
    id: '1',
    title: '永', 
    image: 'https://s1.mintiny.com/wlake/i/2024/12/22/6okxq.png' 
  },
  { 
    id: '2',
    title: '是', 
    image: 'https://s1.mintiny.com/wlake/i/2024/12/22/1amx4i.png' 
  },
  { 
    id: '3',
    title: '者', 
    image: 'https://s1.mintiny.com/wlake/i/2024/12/22/1amwey.png' 
  },
  { 
    id: '4',
    title: '马', 
    image: 'https://s1.mintiny.com/wlake/i/2024/12/22/6nure.png' 
  },
  { 
    id: '5',
    title: '字', 
    image: 'https://s1.mintiny.com/wlake/i/2024/12/22/1amyhl.png' 
  },
  { 
    id: '6',
    title: '神', 
    image: 'https://s1.mintiny.com/wlake/i/2024/12/22/1amz9k.png' 
  },
];

// 添加计算属性来获取后续三个字符
const nextCharacters = computed(() => {
  const currentId = route.params.id as string;
  const currentIndex = allCharacters.findIndex(char => char.id === currentId);
  if (currentIndex === -1) return [];
  
  // 获取后续三个字符，如果到达末尾则从头开始
  const result = [];
  for (let i = 1; i <= 3; i++) {
    const nextIndex = (currentIndex + i) % allCharacters.length;
    result.push(allCharacters[nextIndex]);
  }
  return result;
});

// 修改计算属性
const currentImage = computed(() => {
  // 优先使用route.params，如果不存在则使用route.query，最后使用默认值
  return (route.params.image as string) || (route.query.image as string) || ziIcon;
});

const currentCharacter = computed(() => {
  return (route.params.character as string) || '永';
});

// 修改watch
watch(() => route.params, (newParams) => {
  if (mainImage.value) {
    mainImage.value.src = currentImage.value
  }
}, { immediate: true })

const goBack = () => {
  router.back()
}

const toggleCollect = () => {
  return
}

const downloadImage = async () => {
  try {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    if (!ctx || !mainImage.value) {
      console.error('Canvas context or main image not available');
      return;
    }

    // 等待图片加载完成
    await new Promise((resolve, reject) => {
      const img = new Image();
      img.crossOrigin = 'anonymous';  // 添加这行以处理跨域图片
      img.onload = () => {
        // 设置canvas尺寸为图片的实际尺寸
        canvas.width = img.naturalWidth;
        canvas.height = img.naturalHeight;
        
        // 绘制图片
        ctx.drawImage(img, 0, 0);

        // 如果是黑白模式，应用黑白效果
        if (isBlackAndWhite.value) {
          const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
          const data = imageData.data;
          for (let i = 0; i < data.length; i += 4) {
            const avg = (data[i] + data[i + 1] + data[i + 2]) / 3;
            data[i] = data[i + 1] = data[i + 2] = avg;
          }
          ctx.putImageData(imageData, 0, 0);
        }

        // 如果选择了线格，绘制线格
        if (selectedGrid.value !== 'none') {
          ctx.strokeStyle = 'rgba(255, 0, 0, 0.2)';
          ctx.lineWidth = 2;

          // 绘制线格逻辑...
          if (selectedGrid.value === 'square') {
            const cellSize = canvas.width / 3;
            ctx.strokeRect(0, 0, canvas.width, canvas.height);
            for (let i = 1; i < 3; i++) {
              ctx.beginPath();
              ctx.moveTo(cellSize * i, 0);
              ctx.lineTo(cellSize * i, canvas.height);
              ctx.moveTo(0, cellSize * i);
              ctx.lineTo(canvas.width, cellSize * i);
              ctx.stroke();
            }
          } else if (selectedGrid.value === 'field') {
            ctx.strokeRect(0, 0, canvas.width, canvas.height);
            ctx.beginPath();
            ctx.moveTo(canvas.width / 2, 0);
            ctx.lineTo(canvas.width / 2, canvas.height);
            ctx.moveTo(0, canvas.height / 2);
            ctx.lineTo(canvas.width, canvas.height / 2);
            ctx.stroke();
          } else if (selectedGrid.value === 'star') {
            ctx.strokeRect(0, 0, canvas.width, canvas.height);
            ctx.beginPath();
            ctx.moveTo(canvas.width / 2, 0);
            ctx.lineTo(canvas.width / 2, canvas.height);
            ctx.moveTo(0, canvas.height / 2);
            ctx.lineTo(canvas.width, canvas.height / 2);
            ctx.moveTo(0, 0);
            ctx.lineTo(canvas.width, canvas.height);
            ctx.moveTo(canvas.width, 0);
            ctx.lineTo(0, canvas.height);
            ctx.stroke();
          }
        }

        resolve(true);
      };
      img.onerror = reject;
      img.src = currentImage.value;
    });

    // 将canvas转换为blob并下载
    canvas.toBlob((blob) => {
      if (blob) {
        const fileName = `${currentCharacter.value}.png`;
        saveAs(blob, fileName);
      }
    }, 'image/png');

  } catch (error) {
    console.error('下载失败:', error);
  }
};

const toggleBlackAndWhite = () => {
  isBlackAndWhite.value = !isBlackAndWhite.value
  
  if (!mainImage.value) return
  
  // 创建一个临时 canvas 来处理图片
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  if (!ctx) return
  
  canvas.width = mainImage.value.naturalWidth
  canvas.height = mainImage.value.naturalHeight
  
  // 绘制原始图片到 canvas
  ctx.drawImage(mainImage.value, 0, 0)
  
  if (isBlackAndWhite.value) {
    // 获取图片数据
    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
    const data = imageData.data
    
    // 使用 OTSU 算法自动计算最佳阈值
    let histogram = new Array(256).fill(0)
    for (let i = 0; i < data.length; i += 4) {
      const avg = Math.round((data[i] + data[i + 1] + data[i + 2]) / 3)
      histogram[avg]++
    }
    
    let sum = 0
    let sumB = 0
    let wB = 0
    let wF = 0
    let max = 0.0
    let threshold = 0
    const total = data.length / 4
    
    for (let i = 0; i < 256; i++) {
      sum += i * histogram[i]
    }
    
    for (let i = 0; i < 256; i++) {
      wB += histogram[i]
      if (wB === 0) continue
      
      wF = total - wB
      if (wF === 0) break
      
      sumB += i * histogram[i]
      
      const mB = sumB / wB
      const mF = (sum - sumB) / wF
      
      const between = wB * wF * (mB - mF) * (mB - mF)
      
      if (between > max) {
        max = between
        threshold = i
      }
    }
    
    // 应用阈值进行二值化
    for (let i = 0; i < data.length; i += 4) {
      const avg = (data[i] + data[i + 1] + data[i + 2]) / 3
      const value = avg > threshold ? 255 : 0
      data[i] = data[i + 1] = data[i + 2] = value
    }
    
    ctx.putImageData(imageData, 0, 0)
    
    // 更新图片源
    const newImageUrl = canvas.toDataURL('image/png')
    mainImage.value.src = newImageUrl
  } else {
    // 恢复原图时使用计算属性的值
    if (mainImage.value) {
      mainImage.value.src = currentImage.value
    }
  }
}

const toggleGridMenu = () => {
  if (selectedGrid.value !== 'none') {
    selectedGrid.value = 'none'
  } else {
    tempSelectedGrid.value = selectedGrid.value
    showGridMenu.value = true
  }
}

const selectGrid = (gridType: 'square' | 'field' | 'star') => {
  tempSelectedGrid.value = gridType
}

const confirmGridSelection = () => {
  selectedGrid.value = tempSelectedGrid.value
  showGridMenu.value = false
}

const selectPreviewImage = (index: number) => {
  const selectedChar = nextCharacters.value[index];
  if (selectedChar) {
    router.push({
      name: 'CharacterDetail',
      params: { 
        id: selectedChar.id,
        character: selectedChar.title,
        image: selectedChar.image,
      },
      query: {
        image: selectedChar.image
      }
    });
  }
};

onMounted(() => {
  console.log('Route params:', route.params);
  console.log('Route query:', route.query);
  console.log('Current image:', currentImage.value);
  
  if (mainImage.value) {
    mainImage.value.src = currentImage.value;
    
    // 添加图片加载错误处理
    mainImage.value.onerror = () => {
      console.error('Failed to load image:', currentImage.value);
      mainImage.value!.src = ziIcon; // 使用默认图片
    };
  }
});
</script>

<style scoped>
.character-detail {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.back-btn,
.collect-btn {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.character-showcase {
  text-align: center;
  margin-bottom: 40px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.function-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
  width: 100%;
  max-width: 400px;
}

.function-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.function-btn {
  padding: 8px 15px;
  font-size: 14px;
  background-color: transparent;
  color: #3498db;
  border: 2px solid #3498db;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s, color 0.3s;
  min-width: 80px;
}

.function-btn:hover {
  background-color: #3498db;
  color: white;
}

.function-btn.active {
  background-color: #3498db;
  color: white;
}

.character-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
  transition: filter 0.3s ease;
}

.character {
  font-size: 36px;
  margin: 0 0 20px 0;
}

.info-section {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}


.info-card h2 {
  font-size: 18px;
  color: #333;
  margin-bottom: 12px;
  font-weight: 500;
}

.info-card p {
  color: #666;
  line-height: 1.6;
  margin: 0;
}

.character-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-top: 20px;
}

.similar-char-item {
  text-align: center;
  padding: 12px;
  cursor: pointer;
  transition: transform 0.2s ease;
  background: #f5f5f5;
  border-radius: 8px;
}

.similar-char-item:hover {
  transform: scale(1.05);
  background: #e8e8e8;
}

.similar-char-item img {
  width: 60px;
  height: 60px;
  object-fit: contain;
  margin-bottom: 8px;
}

.similar-char-item span {
  display: block;
  font-size: 14px;
  color: #333;
}

.collect-btn.collected {
  color: #ffd700;
}

.character-image.black-and-white {
  filter: grayscale(100%);
}

.image-container {
  position: relative;
  width: 200px;  /* 修改为200px宽度 */
  height: 200px; /* 保持1:1比例 */
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
}

.grid-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  border: 2px solid rgba(255, 0, 0, 0.2);
}

.grid-square {
  background-image: linear-gradient(to right, rgba(255, 0, 0, 0.2) 1px, transparent 1px),
                    linear-gradient(to bottom, rgba(255, 0, 0, 0.2) 1px, transparent 1px);
  background-size: 33.33% 33.33%;
}

.grid-field {
  &::before, &::after {
    content: '';
    position: absolute;
    background: rgba(255, 0, 0, 0.2);
  }
  &::before {
    top: 50%;
    left: 0;
    width: 100%;
    height: 1.5px;
  }
  &::after {
    left: 50%;
    top: 0;
    width: 1.5px;
    height: 100%;
  }
}

.grid-star {
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: 
      linear-gradient(45deg, transparent 49.5%, rgba(255, 0, 0, 0.2) 49.5%, rgba(255, 0, 0, 0.2) 50.5%, transparent 50.5%),
      linear-gradient(-45deg, transparent 49.5%, rgba(255, 0, 0, 0.2) 49.5%, rgba(255, 0, 0, 0.2) 50.5%, transparent 50.5%),
      linear-gradient(to right, transparent 49.5%, rgba(255, 0, 0, 0.2) 49.5%, rgba(255, 0, 0, 0.2) 50.5%, transparent 50.5%),
      linear-gradient(to bottom, transparent 49.5%, rgba(255, 0, 0, 0.2) 49.5%, rgba(255, 0, 0, 0.2) 50.5%, transparent 50.5%);
  }
}

.grid-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.grid-dialog :deep(.el-dialog__header) {
  margin-right: 0;
  padding: 20px 20px 10px;
}

.grid-dialog :deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 500;
}

.grid-dialog :deep(.el-dialog__footer) {
  padding: 10px 20px 20px;
  border-top: none;
}

.grid-options {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  padding: 10px;
  width: fit-content;
  margin: 0 auto;
}

.grid-option {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 10px;
  border-radius: 8px;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.grid-option:hover {
  background-color: #f5f5f5;
}

.grid-option.active {
  background-color: #e6f7ff;
  border: 2px solid #3498db;
  transform: scale(1.05);
}

.grid-preview {
  width: 60px;
  height: 60px;
  border: 1px solid #ddd;
  border-radius: 4px;
  position: relative;
  background-color: white;
}

.preview-square {
  border: 1px solid rgba(255, 0, 0, 0.2);
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
  gap: 0;
  & > div {
    border-right: 1px solid rgba(255, 0, 0, 0.2);
    border-bottom: 1px solid rgba(255, 0, 0, 0.2);
    &:nth-child(3n) {
      border-right: none;
    }
    &:nth-child(n+7) {
      border-bottom: none;
    }
  }
}

.preview-field {
  position: relative;
  &::before, &::after {
    content: '';
    position: absolute;
    background: rgba(255, 0, 0, 0.2);
  }
  &::before {
    top: 50%;
    left: 0;
    width: 100%;
    height: 1px;
  }
  &::after {
    left: 50%;
    top: 0;
    width: 1px;
    height: 100%;
  }
  border: 1px solid rgba(255, 0, 0, 0.2);
}

.preview-star {
  position: relative;
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: 
      linear-gradient(45deg, transparent 49.5%, rgba(255, 0, 0, 0.2) 49.5%, rgba(255, 0, 0, 0.2) 50.5%, transparent 50.5%),
      linear-gradient(-45deg, transparent 49.5%, rgba(255, 0, 0, 0.2) 49.5%, rgba(255, 0, 0, 0.2) 50.5%, transparent 50.5%),
      linear-gradient(to right, transparent 49.5%, rgba(255, 0, 0, 0.2) 49.5%, rgba(255, 0, 0, 0.2) 50.5%, transparent 50.5%),
      linear-gradient(to bottom, transparent 49.5%, rgba(255, 0, 0, 0.2) 49.5%, rgba(255, 0, 0, 0.2) 50.5%, transparent 50.5%);
  }
  border: 1px solid rgba(255, 0, 0, 0.2);
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding-top: 20px;
}

.dialog-btn {
  min-width: 80px;
}

.collect-btn {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  color: #ffd700;
  cursor: default;
}

.collect-btn:hover {
  background: #fff;
}

.collect-btn.collected {
  color: #ffd700;
}
</style> 